#include <math.h>
#include <vector>
#include <string>

#include <gdk/gdkkeysyms.h>

#include "qaholom.h"
#include "qahcontrols.h"
#include "qahcontainer.h"
#include "qahsighandlers.h"
#include "drawingtool.h"

#include "zoota-common.h"


using namespace std;

////////////////////////////////////////////////////////////////////////////////
// TechLine Calculation

void CAL5DAYAVGPRICE()
{
   int size = twStockData.size();
   double total = 0.0;
   
   tw5DaysAveragePrice.resize(size);
   
   for (int i = 0; i < 4; i++)
   {
      total += twStockData[i].txClose;
      
      tw5DaysAveragePrice[i].txDate       = twStockData[i].txDate;
      tw5DaysAveragePrice[i].averagePrice = total / (i + 1);
   }
   
   for (int i = 4; i < size; i++)
   {
      total  = tw5DaysAveragePrice[i-1].averagePrice * 0.8;
      total += twStockData[i].txClose * 0.2;
      
      tw5DaysAveragePrice[i].txDate       = twStockData[i].txDate;
      tw5DaysAveragePrice[i].averagePrice = total;      
   }
   
   return;
}

void CAL21DAYAVGPRICE()
{
   int size = twStockData.size();
   double total = 0.0;
   
   tw21DaysAveragePrice.resize(size);
   
   for (int i = 0; i < 21; i++)
   {
      total += twStockData[i].txClose;
      
      tw21DaysAveragePrice[i].txDate       = twStockData[i].txDate;
      tw21DaysAveragePrice[i].averagePrice = total / (i + 1);
   }
   
   for (int i = 21; i < size; i++)
   {
      total  = tw21DaysAveragePrice[i-1].averagePrice * 0.9524;
      total += twStockData[i].txClose * 0.0476;
      
      tw21DaysAveragePrice[i].txDate       = twStockData[i].txDate;
      tw21DaysAveragePrice[i].averagePrice = total;      
   }
   
   return;
}
////////////////////////////////////////////////////////////////////////////////
// Importing trading data

int ReadYahooData()
{
   FILE* fp;
   RAWDATA txData;
   double maxPrice, minPrice;

   maxPrice = 0;
   minPrice = 99999999.99;
   char buf[512];
   
   fp = fopen("yahoo.dat", "r");
   fgets(buf, 511, fp);  // drop the head line that is the title
   
   while ( NULL != fgets(buf, 511, fp))
   {
      char sep[] = ",\n";
      //Date,Open,High,Low,Close,Volume,Adj Close
      
      char* fields[7];
      
      fields[0] = strtok(buf, sep);
      fields[1] = strtok(NULL, sep);
      fields[2] = strtok(NULL, sep);
      fields[3] = strtok(NULL, sep);
      fields[4] = strtok(NULL, sep);
      fields[5] = strtok(NULL, sep);
      fields[6] = strtok(NULL, sep);
      
      TRADINGDAY td;
      char sep1[] = "-";
   
      td.txDate   = (atoi(strtok(fields[0], sep1)) - 2000) * 10000;
      td.txDate  += atoi(strtok(NULL, sep1)) * 100;
      td.txDate  += atoi(strtok(NULL, sep1));
      
      td.txOpen   = atof(fields[1]);
      td.txHigh   = atof(fields[2]);
      td.txLow    = atof(fields[3]);
      td.txClose  = atof(fields[4]);
      td.txVolume = atof(fields[5]);
      
      vector<TRADINGDAY>::iterator  iter = twStockData.begin();
      
      twStockData.insert(iter, td);
   } 
   
   return 0;
}

int ReadStockData() 
{
   FILE* fp;
   RAWDATA txData;
   unsigned char* buf = reinterpret_cast<unsigned char*>(&txData);
   double maxPrice, minPrice;
   
   size_t  len = 0;
   
   maxPrice = 0;
   minPrice  = 9999999.99;
   
   fp = fopen("IDXWT.DAT", "rb");
   
   while ((len = fread(buf, sizeof(RAWDATA), 1, fp)) == 1) 
   {
      TRADINGDAY td;

      if (txData.txDate <= 930101)
         continue;
                  
      td.txDate   = txData.txDate;
      td.txOpen   = 0.01 * txData.txOpen;
      td.txHigh   = 0.01 * txData.txHigh;
      td.txLow    = 0.01 * txData.txLow;
      td.txClose  = 0.01 * txData.txClose;
      td.txVolume =  txData.txVolume; 

      twStockData.push_back(td);
      
      maxPrice = max(td.txHigh, maxPrice);
      minPrice = min(td.txLow, minPrice);
   }
   
   return 0;
}

///////////////////////////////////////////////////////////////////////////////
   


int main(int argc, char* argv[]) 
{
   QahApplication  qaholom;
      
   qaholom.init(argc, argv);
 
   QahWindow  window;
   
   ZoMarketChart market_chart(150, 400);
   ZoTeklineChart tekline_area1(200, 100), tekline_area2(200, 100);
   
   QahDrawArea& qarea = market_chart;
   QahDrawArea& area1 = tekline_area1;
   QahDrawArea& area2 = tekline_area2;
   
   // >>> coding style 1:
   //window.setTitle("Qaholom - The Most Powerful Technical Analysis Software");
   //window.setDefaultSize(700, 500);
   //window.setPosition(GTK_WIN_POS_CENTER);
   
   // >>> coding style 2:
   window.title    = "Qaholom - The Most Powerful Technical Analysis Software";
   window.height   = 640;
   window.width    = 1125;
   window.position = GTK_WIN_POS_CENTER;
   
   // >>> coding style 3:
   // window.propertyAs("title", "...", 
   //                   "default-height", 640, 
   //                   "default-width", 1024, 
   //                   "window-position", GTK_WIN_POS_CENTER,
   //                   NULL);
      
   QahVBox  vbox, vbox2;
   QahHBox  hbox,hbox1;
   QahVPaned vpaned;
   QahHPaned hpaned;
   QahButton button("Analysis"), button1("index"), button2("_Model it");
   QahComboBox combox;
   QahNotebook notebook, notebook1;
   QahLabel description("put some text here.");
   QahCheckButton check1("_log scale"), check2("_arithmetic scale");
   
   vbox.homogeneous  = false;
   vbox2.homogeneous = false;
   hbox.homogeneous  = false;
   hbox1.homogeneous = false;

   /*
   combox.appendText("TWEX-2337", "TWEX-1001", "TWEX-8567", "TWEX-2354", "TWEX-4342");   
   
   window.contain(hbox);
   hbox.contain(vbox);
   vbox.contain(hbox1, false, true, 1);
   hbox1.contain(combox);
   hbox1.contain(button, false, true, 1);
   hbox1.contain(check1, false, true, 1);
   hbox1.contain(check2, false, true, 1);
   // hbox1.contain(button, check1, check2, PACKINGINFO(false, true, 1));   
   vbox.contain(vpaned);
   vpaned.contain(1, qarea);
   vbox2.contain(techlineArea, volumeArea);
   vpaned.contain(2, vbox2);
   hbox.contain(notebook, false, true, 1);
   notebook.contain("Options", button1);
   notebook.contain("MSCI description", description);
   notebook.contain("Modeling", button2);
   */
   
   //QahMenuBar menubar(main_menu.createMenuBar());
   
   //menubar.append(QahMenuItem("_File", 001));
   //menubar.append(QahMenuItem("_Help", 002));
   
   window.contain(hbox);
   
   hbox.contain(notebook);
   hbox.contain(notebook1, false, false, 0);
   
   //vbox2.contain(menubar, false, true, 0);
   notebook.contain("Markets", vpaned);
   notebook.contain("8567.TW", description);
   notebook.contain("2459.TW", description);
   notebook.contain("2603.TW", description);

   notebook1.contain("Targets", button);
   notebook1.contain("Line", button);
   notebook1.contain("Notes", button);
   vpaned.contain(1, qarea);
   vpaned.contain(2, vbox2);
   vbox2.contain(area1, area2);
   
   
   // .:: IMPORTING DATA ::.
   
   if (argv[1])
   {
      switch (argv[1][0]) 
      {
         case 'Z':
         case 'z':
            ReadStockData();  // reading stock trading data from ezchart... :)
            break;
         case 'Y':
         case 'y':
            ReadYahooData(); // reading trading data from yahoo ... OIH
            break;
         default:
            g_print("unreconized parameter!!  now we will terminate ... \n");
            exit(-1);
            break;
      }
   }
   else // using default data source
   {
      ReadYahooData(); 
   }

   // .:: CALCULATING TEKLINE ::.
   
   CAL5DAYAVGPRICE();
   CAL21DAYAVGPRICE();
   
   // .:: SIGNAL CONNECTING ::.
      
   gtk_widget_add_events (qarea.egoWidget, 
                          GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK |
                          GDK_KEY_PRESS_MASK );
 
   ON_EXPOSE(qarea);
   ON_BUTTON_PRESSED(qarea);   
   ON_MOUSE_MOVED(qarea);
   ON_KEY_PRESSED(qarea);

   gtk_widget_add_events (area1.egoWidget, 
                          GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK |
                          GDK_KEY_PRESS_MASK );
   
   ON_EXPOSE(area1);
   ON_EXPOSE(area2);
                    
   ON_BUTTON_PRESSED(area1);
                                                
   g_signal_connect(GTK_WIDGET(window.egoWidget), "delete-event", 
                    G_CALLBACK(gtk_widget_destroy), NULL);
   
   g_signal_connect(GTK_WIDGET(window.egoWidget), "destroy", G_CALLBACK(gtk_main_quit), NULL);
   
   
   qarea.canFocus = true;                       
   gtk_widget_grab_focus (qarea.egoWidget);               
   
   window.showAll();  
    
   qaholom.run();
   return 0;
}
